<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/icon.png">
  <link rel="mask-icon" href="/blog/images/icon.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bgape002.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="GILGIL全称Global Interpreter Lock，全局解释器锁。GIL并不是Python语言的特性，它是在实现Python解释器时引用的一个概念。GIL只在CPython解释器上存在。 在使用互斥锁解决代码中的资源竞争问题时，当一个线程执行时，会将全局共享的资源上锁，当线程执行完成后，将锁解开，释放资源，其他线程才能够使用。GIL的作用与互斥锁的作用相似，是为了解决解释器中多个线程资">
<meta property="og:type" content="article">
<meta property="og:title" content="python process&amp;thread">
<meta property="og:url" content="https://bgape002.gitee.io/2022/07/05/python-process-thread/index.html">
<meta property="og:site_name" content="bgape002">
<meta property="og:description" content="GILGIL全称Global Interpreter Lock，全局解释器锁。GIL并不是Python语言的特性，它是在实现Python解释器时引用的一个概念。GIL只在CPython解释器上存在。 在使用互斥锁解决代码中的资源竞争问题时，当一个线程执行时，会将全局共享的资源上锁，当线程执行完成后，将锁解开，释放资源，其他线程才能够使用。GIL的作用与互斥锁的作用相似，是为了解决解释器中多个线程资">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-07-05T03:29:57.000Z">
<meta property="article:modified_time" content="2022-07-07T08:49:28.629Z">
<meta property="article:author" content="bgape002">
<meta property="article:tag" content="process">
<meta property="article:tag" content="thread">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://bgape002.gitee.io/2022/07/05/python-process-thread/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>python process&thread | bgape002</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">bgape002</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">淡泊明志，宁静致远</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">66</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">27</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">61</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bgape002.gitee.io/2022/07/05/python-process-thread/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/head.png">
      <meta itemprop="name" content="bgape002">
      <meta itemprop="description" content="mail: bgape002@163.com">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="bgape002">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          python process&thread
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2022-07-05 11:29:57" itemprop="dateCreated datePublished" datetime="2022-07-05T11:29:57+08:00">2022-07-05</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2022-07-07 16:49:28" itemprop="dateModified" datetime="2022-07-07T16:49:28+08:00">2022-07-07</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/blog/2022/07/05/python-process-thread/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/blog/2022/07/05/python-process-thread/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="GIL"><a href="#GIL" class="headerlink" title="GIL"></a>GIL</h2><p>GIL全称<code>Global Interpreter Lock</code>，全局解释器锁。GIL并不是<code>Python</code>语言的特性，它是在实现<code>Python</code>解释器时引用的一个概念。GIL只在<code>CPython</code>解释器上存在。</p>
<p>在使用互斥锁解决代码中的资源竞争问题时，当一个线程执行时，会将全局共享的资源上锁，当线程执行完成后，将锁解开，释放资源，其他线程才能够使用。<strong>GIL的作用与互斥锁的作用相似，是为了解决解释器中多个线程资源竞争的问题。</strong></p>
<h3 id="GIL对程序的影响"><a href="#GIL对程序的影响" class="headerlink" title="GIL对程序的影响"></a>GIL对程序的影响</h3><ul>
<li>因为GIL的存在，在Python中同一时刻有且只有一个线程会执行。</li>
<li>因为线程是存在于进程中的，线程是CPU调度和分派的基本单位，Python中的<strong>多线程由于GIL锁的存在无法利用多核 CPU</strong>。</li>
<li>GIL在程序中有IO操作时才切换到其他线程，所以Python中的多线程不适合计算密集型的程序，只适合IO密集型的程序。</li>
<li>GIL保证单个字节码的执行不会受到其他线程的任何干扰，但是<strong>任何字节码间都可能发生线程切换</strong>。</li>
</ul>
<span id="more"></span>

<h2 id="并行与并发"><a href="#并行与并发" class="headerlink" title="并行与并发"></a>并行与并发</h2><p>几乎所有的操作系统都支持同时运行多个任务，每个任务通常是一个程序，每一个运行中的程序就是一个进程，即进程是应用程序的执行实例。</p>
<h3 id="并行"><a href="#并行" class="headerlink" title="并行"></a>并行</h3><p>并行指在同一时刻有多条指令在多个处理器上<strong>同时执行</strong>；</p>
<h3 id="并发"><a href="#并发" class="headerlink" title="并发"></a>并发</h3><p>并发是指在同一时刻只能有一条指令执行，但多个进程指令被<strong>快速轮换执行</strong>，使得在宏观上具有多个进程同时执行的效果</p>
<h2 id="线程与进程"><a href="#线程与进程" class="headerlink" title="线程与进程"></a>线程与进程</h2><p>进程和线程的关系是这样的：<strong>操作系统可以同时执行多个任务，每一个任务就是一个进程，进程可以同时执行多个任务，每一个任务就是一个线程。</strong></p>
<h3 id="线程"><a href="#线程" class="headerlink" title="线程"></a>线程</h3><p>线程是<strong>程序执行</strong>的最小单位，是进程的组成部分，一个进程可以拥有多个线程。在多线程中，会有<strong>一个主线程来完成整个进程从开始到结束的全部操作</strong>，而其他的线程会在主线程的运行过程中被创建或退出。</p>
<ul>
<li><strong>线程安全：</strong>多线程竞争同一个资源保证数据一致性和完整性的一个过程，通常一般是采取加锁机制，进行相关数据临界点的互斥。</li>
<li><strong>线程安全一般是：</strong>多线程环境下对一些【全局变量及静态变量】引起的同时具有【写操作权限】的时候会出现数据不一致或数据污染的情况，此时会了避免此类情况的发生，一般采取就是加锁的机制。</li>
</ul>
<h3 id="进程"><a href="#进程" class="headerlink" title="进程"></a>进程</h3><p>是<strong>资源分配</strong>的最小单位，它是操作系统进行资源分配（CPU，内存，磁盘，网络）和调度运行的基本单位，一个程序就是一个进程</p>
<h2 id="多线程"><a href="#多线程" class="headerlink" title="多线程"></a>多线程</h2><h3 id="threading"><a href="#threading" class="headerlink" title="threading"></a><code>threading</code></h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">func1</span>(<span class="params">p1, p2</span>):</span><br><span class="line">    <span class="built_in">print</span>(p1)</span><br><span class="line">    time.sleep(<span class="number">2</span>)</span><br><span class="line">    <span class="built_in">print</span>(p2)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">func2</span>():</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;print 2-1th&#x27;</span>)</span><br><span class="line">    time.sleep(<span class="number">4</span>)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;print 2-2th&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    thd1 = threading.Thread(target=func1, args=(<span class="string">&#x27;1-1th&#x27;</span>, <span class="string">&#x27;1-2th&#x27;</span>,))</span><br><span class="line">    thd2 = threading.Thread(target=func2)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 设置守护进程，在主进程结束时，守护进程会直接结束</span></span><br><span class="line">    thd2.setDaemon(<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">    thd1.start()</span><br><span class="line">    thd2.start()</span><br><span class="line"></span><br><span class="line">    tm1 = time.time()</span><br><span class="line">    <span class="comment"># 设置进程阻塞，等带join进程运行完成</span></span><br><span class="line">    thd1.join()</span><br><span class="line">    tm2 = time.time()</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;程序结束,进程阻塞时间为：&#123;&#125;&#x27;</span>.<span class="built_in">format</span>(<span class="built_in">round</span>(tm2-tm1, <span class="number">2</span>)))</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;output</span></span><br><span class="line"><span class="string">1-1th</span></span><br><span class="line"><span class="string">print 2-1th</span></span><br><span class="line"><span class="string">1-2th</span></span><br><span class="line"><span class="string">程序结束,进程阻塞时间为：2.02</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<ul>
<li><p><strong>由于<code>th2</code>设置了<code>daemon</code>守护进程，主线程<code>3s</code>内运行完成，故无法输出<code>print 2-2th</code></strong></p>
</li>
<li><p><strong>由于<code>th1</code>设置了<code>join</code>阻塞主进程，<code>th1</code>线程运行完成需要<code>2s</code>，故最后一个打印会阻塞<code>2.02s</code></strong></p>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;多线程编程模式2：</span></span><br><span class="line"><span class="string">继承thread类</span></span><br><span class="line"><span class="string">---</span></span><br><span class="line"><span class="string">适用于进程代码较为复杂的程序编程</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Thread1</span>(threading.Thread):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, args, name</span>):</span><br><span class="line">        <span class="built_in">super</span>().__init__(name=name)  <span class="comment"># 设置进程名称</span></span><br><span class="line">        self.p1 = args[<span class="number">0</span>]</span><br><span class="line">        self.p2 = args[<span class="number">1</span>]</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">run</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(self.p1)</span><br><span class="line">        time.sleep(<span class="number">2</span>)</span><br><span class="line">        <span class="built_in">print</span>(self.p2)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Thread2</span>(threading.Thread):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">run</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;print 2-1th&#x27;</span>)</span><br><span class="line">        time.sleep(<span class="number">4</span>)</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&#x27;print 2-2th&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    thd1 = Thread1((<span class="string">&#x27;1-1th&#x27;</span>, <span class="string">&#x27;2-1th&#x27;</span>), <span class="string">&#x27;thread1&#x27;</span>)</span><br><span class="line">    thd2 = Thread2()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 设置守护进程，在其他进程结束时，守护进程会直接结束</span></span><br><span class="line">    thd2.setDaemon(<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">    thd1.start()</span><br><span class="line">    thd2.start()</span><br><span class="line"></span><br><span class="line">    tm1 = time.time()</span><br><span class="line">    <span class="comment"># 设置进程阻塞，等带join进程运行完成</span></span><br><span class="line">    thd1.join()</span><br><span class="line">    tm2 = time.time()</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;程序结束,进程阻塞时间为：&#123;&#125;&#x27;</span>.<span class="built_in">format</span>(<span class="built_in">round</span>(tm2 - tm1, <span class="number">2</span>)))</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">1-1th</span></span><br><span class="line"><span class="string">print 2-1th</span></span><br><span class="line"><span class="string">2-1th</span></span><br><span class="line"><span class="string">程序结束,进程阻塞时间为：2.0</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h3 id="线程通信"><a href="#线程通信" class="headerlink" title="线程通信"></a>线程通信</h3><ul>
<li><p>线程间的通信方式</p>
<ul>
<li><p>共享变量，设置一个可共享的全局变量（通信过程中，线程不安全）</p>
</li>
<li><p><code>queue</code>、<code>q = queue.Queue()</code> ，常用方法有</p>
</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Queue.qsize() 返回队列的大小</span><br><span class="line">Queue.empty() 如果队列为空，返回True,反之False</span><br><span class="line">Queue.full() 如果队列满了，返回True,反之False</span><br><span class="line">Queue.full 与 maxsize 大小对应</span><br><span class="line">Queue.get([block[, timeout]])获取队列，timeout等待时间</span><br><span class="line">Queue.get_nowait() 相当Queue.get(False)</span><br><span class="line">Queue.put(item) 写入队列，timeout等待时间</span><br><span class="line">Queue.put_nowait(item) 相当Queue.put(item, False)</span><br><span class="line">Queue.task_done() 在完成一项工作之后，Queue.task_done()函数向任务已经完成的队列发送一个信号</span><br><span class="line">Queue.join() 实际上意味着等到队列为空，再执行别的操作</span><br></pre></td></tr></table></figure>

</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> queue</span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line">exitFlag = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">myThread</span> (threading.Thread):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, threadID, name, q</span>):</span><br><span class="line">        threading.Thread.__init__(self)</span><br><span class="line">        self.threadID = threadID</span><br><span class="line">        self.name = name</span><br><span class="line">        self.q = q</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">run</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="built_in">print</span> (<span class="string">&quot;开启线程：&quot;</span> + self.name)</span><br><span class="line">        process_data(self.name, self.q)</span><br><span class="line">        <span class="built_in">print</span> (<span class="string">&quot;退出线程：&quot;</span> + self.name)</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">process_data</span>(<span class="params">threadName, q</span>):</span><br><span class="line">    <span class="keyword">while</span> <span class="keyword">not</span> exitFlag:</span><br><span class="line">        queueLock.acquire()</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> workQueue.empty():</span><br><span class="line">            data = q.get()</span><br><span class="line">            queueLock.release()</span><br><span class="line">            <span class="built_in">print</span> (<span class="string">&quot;%s processing %s&quot;</span> % (threadName, data))</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            queueLock.release()</span><br><span class="line">        time.sleep(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line">threadList = [<span class="string">&quot;Thread-1&quot;</span>, <span class="string">&quot;Thread-2&quot;</span>, <span class="string">&quot;Thread-3&quot;</span>]</span><br><span class="line">nameList = [<span class="string">&quot;One&quot;</span>, <span class="string">&quot;Two&quot;</span>, <span class="string">&quot;Three&quot;</span>, <span class="string">&quot;Four&quot;</span>, <span class="string">&quot;Five&quot;</span>]</span><br><span class="line">queueLock = threading.Lock()</span><br><span class="line">workQueue = queue.Queue(<span class="number">10</span>)</span><br><span class="line">threads = []</span><br><span class="line">threadID = <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 创建新线程</span></span><br><span class="line"><span class="keyword">for</span> tName <span class="keyword">in</span> threadList:</span><br><span class="line">    thread = myThread(threadID, tName, workQueue)</span><br><span class="line">    thread.start()</span><br><span class="line">    threads.append(thread)</span><br><span class="line">    threadID += <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 填充队列</span></span><br><span class="line">queueLock.acquire()</span><br><span class="line"><span class="keyword">for</span> word <span class="keyword">in</span> nameList:</span><br><span class="line">    workQueue.put(word)</span><br><span class="line">queueLock.release()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 等待队列清空</span></span><br><span class="line"><span class="keyword">while</span> <span class="keyword">not</span> workQueue.empty():</span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 通知线程是时候退出</span></span><br><span class="line">exitFlag = <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 等待所有线程完成</span></span><br><span class="line"><span class="keyword">for</span> t <span class="keyword">in</span> threads:</span><br><span class="line">    t.join()</span><br><span class="line"><span class="built_in">print</span> (<span class="string">&quot;退出主线程&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;output</span></span><br><span class="line"><span class="string">开启线程：Thread-1</span></span><br><span class="line"><span class="string">开启线程：Thread-2</span></span><br><span class="line"><span class="string">开启线程：Thread-3</span></span><br><span class="line"><span class="string">Thread-2 processing One</span></span><br><span class="line"><span class="string">Thread-3 processing Two</span></span><br><span class="line"><span class="string">Thread-1 processing Three</span></span><br><span class="line"><span class="string">Thread-1 processing FourThread-3 processing Five</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">退出线程：Thread-3退出线程：Thread-1</span></span><br><span class="line"><span class="string">退出线程：Thread-2</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h3 id="线程同步"><a href="#线程同步" class="headerlink" title="线程同步"></a>线程同步</h3><ul>
<li><p>线程锁<code>Lock</code></p>
<ul>
<li><code>Lock</code>会影响性能，<code>Lock</code>锁一个进程使用后必须释放，否则其他进程无法执行会一直等待</li>
<li><code>Lock</code>引起死锁（资源未释放、循环等待）</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string"> 加锁可以保证一次计算和赋值操作完成后再让出资源</span></span><br><span class="line"><span class="string"> ---</span></span><br><span class="line"><span class="string"> 线程锁的概念有点类似于数据库中的事务锁，让可能不安全的操作具有原子性</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line">lock=threading.Lock()  <span class="comment"># 创建一个锁</span></span><br><span class="line">number=<span class="number">0</span></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">addNumber</span>():</span><br><span class="line">    <span class="keyword">global</span> number</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1000000</span>):</span><br><span class="line">       </span><br><span class="line">        lock.acquire() <span class="comment"># 上锁</span></span><br><span class="line">        number+=<span class="number">1</span></span><br><span class="line">        lock.release()  <span class="comment"># 释放锁</span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">downNumber</span>():</span><br><span class="line">    <span class="keyword">global</span> number</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1000000</span>):</span><br><span class="line">        lock.acquire()</span><br><span class="line">        number-=<span class="number">1</span></span><br><span class="line">        lock.release()</span><br><span class="line"> </span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;start&#x27;</span>)</span><br><span class="line">    t=threading.Thread(target=addNumber)</span><br><span class="line">    t2=threading.Thread(target=downNumber)</span><br><span class="line">    t.start()</span><br><span class="line">    t2.start()</span><br><span class="line">    t.join()</span><br><span class="line">    t2.join()</span><br><span class="line">    <span class="built_in">print</span>(number)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;stop&#x27;</span>)</span><br></pre></td></tr></table></figure></li>
<li><p><code>Rlock</code>可重入锁，同一线程内可多次调用<code>acquire</code>,但需注意调用几次对应<code>release</code>几次</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> threading <span class="keyword">import</span> Thread, RLock</span><br><span class="line"><span class="keyword">from</span> time <span class="keyword">import</span> sleep</span><br><span class="line"></span><br><span class="line">lock = RLock()</span><br><span class="line">fridges = [<span class="number">0</span> <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>)]    <span class="comment">#10个冰箱</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">e2f</span>():</span><br><span class="line">    <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>):</span><br><span class="line">        <span class="keyword">if</span> fridges[x]==<span class="number">0</span>:</span><br><span class="line">            sleep(<span class="number">0.1</span>)      <span class="comment">#装冰箱需要一点时间→_→</span></span><br><span class="line">            fridges[x] += <span class="number">1</span></span><br><span class="line">            <span class="keyword">return</span> x</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">E2FwithLock</span>(<span class="params">L</span>):</span><br><span class="line">    <span class="keyword">while</span>(<span class="literal">True</span>):</span><br><span class="line">        <span class="keyword">if</span> L.acquire(<span class="literal">False</span>):	<span class="comment">#把冰箱门打开</span></span><br><span class="line">            e2f()</span><br><span class="line">            L.release()			<span class="comment">#把冰箱门关上</span></span><br><span class="line"></span><br><span class="line">ths = [Thread(target=E2FwithLock,args=[lock]) <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">10</span>)]</span><br><span class="line"><span class="keyword">for</span> t <span class="keyword">in</span> ths: t.start()</span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
<li><p>条件变量<code>condition</code></p>
<ul>
<li>类内实现了<code>_enter_(self)</code>和<code>_exit_(self)</code>方法，便可以使用with对类进行上下文管理</li>
</ul>
</li>
<li><p>信号量<code>semaphore</code></p>
<ul>
<li>用于控制进入数量的锁，允许程序同时刻的并发数</li>
</ul>
</li>
</ul>
<h3 id="线程池"><a href="#线程池" class="headerlink" title="线程池"></a>线程池</h3><ul>
<li><code>ThreadPoolExecutor</code>:–&gt;<code>from concurrent import futures//from concurrent.futures import ThreadPoolExecutor</code></li>
</ul>
<h2 id="多进程"><a href="#多进程" class="headerlink" title="多进程"></a>多进程</h2><h3 id="multiprocessing"><a href="#multiprocessing" class="headerlink" title="multiprocessing"></a><code>multiprocess</code>ing</h3><h3 id="进程池"><a href="#进程池" class="headerlink" title="进程池"></a>进程池</h3><ul>
<li><code>ProcessPoolExecutor</code>:–&gt;<code>from concurrent.futures import ProcessPoolExecutor</code></li>
<li><code>from multiprocessing import pool</code></li>
</ul>
<h3 id="进程通信"><a href="#进程通信" class="headerlink" title="进程通信"></a>进程通信</h3><ul>
<li><p>多进程之间的数据是隔离的，相互独立的</p>
</li>
<li><p><code>Queue</code></p>
<ul>
<li><p><code>queque.Queue</code>不能用于<code>multiprocessing.process()</code>；可以使用<code>multiprocessing.Queue</code></p>
</li>
<li><p><code>multiprocessing</code>中的<code>Queue</code>不能用于<code>pool</code>进程池；<code>pool</code>中的进程间通信可以使用``multiprocessing.manager<code>中的</code>Queue`方法</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> queue <span class="keyword">import</span> Queue</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> multiprocessing <span class="keyword">import</span> Queue</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> multiprocessing <span class="keyword">import</span> manager</span><br><span class="line">Manager().Queue</span><br></pre></td></tr></table></figure></li>
<li><p>通过<code>Pile</code>管道通信，只能用于两个进程间的通信</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> multiprocessing <span class="keyword">import</span> Process, Pipe</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">producer</span>(<span class="params">pipe</span>):</span><br><span class="line">    pipe.send(<span class="string">&quot;bgape&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">consumer</span>(<span class="params">pipe</span>):</span><br><span class="line">    <span class="built_in">print</span>(pipe.recv())</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    recvPipe, sendPipe = Pipe()</span><br><span class="line">    prod = Process(target=producer, args=(sendPipe,))</span><br><span class="line">    cons = Process(target=consumer, args=(recvPipe,))</span><br><span class="line">    prod.start()</span><br><span class="line">    cons.start()</span><br><span class="line">    prod.join()</span><br><span class="line">    cons.join()</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line"><span class="string">&quot;&quot;&quot;output</span></span><br><span class="line"><span class="string">bgape</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure></li>
<li><p>利用<code>Manager</code>维护进程间的共享内存</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> multiprocessing <span class="keyword">import</span> Process, Manager</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">producer</span>(<span class="params">pDict, key, value</span>):</span><br><span class="line">    pDict[key] = value</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    procDict = Manager().<span class="built_in">dict</span>()</span><br><span class="line">    proc1 = Process(target=producer, args=(procDict, <span class="number">1</span>, <span class="string">&#x27;bgape002&#x27;</span>))</span><br><span class="line">    proc2 = Process(target=producer, args=(procDict, <span class="number">2</span>, <span class="string">&#x27;bgape003&#x27;</span>))</span><br><span class="line"></span><br><span class="line">    proc1.start()</span><br><span class="line">    proc2.start()</span><br><span class="line">    proc1.join()</span><br><span class="line">    proc2.join()</span><br><span class="line"></span><br><span class="line">    <span class="built_in">print</span>(procDict)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;output</span></span><br><span class="line"><span class="string">&#123;1: &#x27;bgape002&#x27;, 2: &#x27;bgape003&#x27;&#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
<li><p><code>Manager</code>可维护的变量类型</p>
<ul>
<li> <code>BoundedSemaphore(self, value: Any = ...) </code></li>
<li> <code>Condition(self, lock: Any = ...) </code></li>
<li><code>Event(self)</code></li>
<li><code>Lock(self) </code></li>
<li><code>Namespace(self)</code></li>
<li> <code>Queue(self, maxsize: int = ...) </code></li>
<li><code> RLock(self)</code></li>
<li><code>Semaphore(self, value: Any = ...)</code></li>
<li> <code>Array(self, typecode: Any, sequence: Sequence[_T])_</code></li>
<li><code> Value(self, typecode: Any, value: _T)_</code></li>
<li><code>dict(self, sequence: Mapping[_KT, _VT] = ...)</code></li>
<li><code>list(self, sequence)</code></li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h3><font size=2>

<p>[1] <a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1zy4y1M7xt?spm_id_from=333.999.0.0&vd_source=5f03bdbb9a8460c7ae08f9cdea23577b">python 高级——多线程、多进程和线程池编程</a></p>
<p>[2] <a target="_blank" rel="noopener" href="https://www.jb51.net/article/216650.htm">Python多线程 Queue 模块常见用法</a></p>
<p>[3] <a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_60823672/article/details/119932638?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-119932638-blog-123888922.pc_relevant_multi_platform_whitelistv1&spm=1001.2101.3001.4242.1&utm_relevant_index=2">python中的线程和进程</a></p>
<p>[4] <a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/200943202">浅析python的GIL</a></p>
<p>[] <a href=""></a></p>
<p></font>&gt;</p>

    </div>

    
    
    

      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/blog/tags/process/" rel="tag"><i class="fa fa-tag"></i> process</a>
              <a href="/blog/tags/thread/" rel="tag"><i class="fa fa-tag"></i> thread</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2022/01/24/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="prev" title="设计模式">
      <i class="fa fa-chevron-left"></i> 设计模式
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2022/07/05/collections-package/" rel="next" title="collections package">
      collections package <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>


        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#GIL"><span class="nav-number">1.</span> <span class="nav-text">GIL</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#GIL%E5%AF%B9%E7%A8%8B%E5%BA%8F%E7%9A%84%E5%BD%B1%E5%93%8D"><span class="nav-number">1.1.</span> <span class="nav-text">GIL对程序的影响</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B9%B6%E8%A1%8C%E4%B8%8E%E5%B9%B6%E5%8F%91"><span class="nav-number">2.</span> <span class="nav-text">并行与并发</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B9%B6%E8%A1%8C"><span class="nav-number">2.1.</span> <span class="nav-text">并行</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B9%B6%E5%8F%91"><span class="nav-number">2.2.</span> <span class="nav-text">并发</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BA%BF%E7%A8%8B%E4%B8%8E%E8%BF%9B%E7%A8%8B"><span class="nav-number">3.</span> <span class="nav-text">线程与进程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BA%BF%E7%A8%8B"><span class="nav-number">3.1.</span> <span class="nav-text">线程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%9B%E7%A8%8B"><span class="nav-number">3.2.</span> <span class="nav-text">进程</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A4%9A%E7%BA%BF%E7%A8%8B"><span class="nav-number">4.</span> <span class="nav-text">多线程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#threading"><span class="nav-number">4.1.</span> <span class="nav-text">threading</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BA%BF%E7%A8%8B%E9%80%9A%E4%BF%A1"><span class="nav-number">4.2.</span> <span class="nav-text">线程通信</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5"><span class="nav-number">4.3.</span> <span class="nav-text">线程同步</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BA%BF%E7%A8%8B%E6%B1%A0"><span class="nav-number">4.4.</span> <span class="nav-text">线程池</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A4%9A%E8%BF%9B%E7%A8%8B"><span class="nav-number">5.</span> <span class="nav-text">多进程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#multiprocessing"><span class="nav-number">5.1.</span> <span class="nav-text">multiprocessing</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%9B%E7%A8%8B%E6%B1%A0"><span class="nav-number">5.2.</span> <span class="nav-text">进程池</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1"><span class="nav-number">5.3.</span> <span class="nav-text">进程通信</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="nav-number">5.4.</span> <span class="nav-text">参考链接</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="bgape002"
      src="/blog/images/head.png">
  <p class="site-author-name" itemprop="name">bgape002</p>
  <div class="site-description" itemprop="description">mail: bgape002@163.com</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">61</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">66</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2021 – 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">bgape002</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'szhBf0Qamzsowubi1WnkXmUj-gzGzoHsz',
      appKey     : 'WpwxoK0fVJHvhzWwakr9vbpA',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
